import React, {useEffect, useState} from "react";
import {Button, Col, DatePicker, Form, Input, message, Modal, Row} from "antd";
import type {Result} from "@/types/result";
import skillCertificateApi from "@/api/skillCertificateApi.ts";
import {SkillCertificate} from "@/types/resp/skillCertificate";
import CandidateSelector from "@/pages/candidate/CandidateSelector.tsx";

interface SkillCertificateAddProps {
  visible: boolean;
  id: number;
  onCloseSkillCertificateAdd: () => void;
}

const SkillCertificateAdd: React.FC<SkillCertificateAddProps> = ({visible, id, onCloseSkillCertificateAdd}) => {

  const [form] = Form.useForm<SkillCertificate>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    candidateName: [
      { required: true, message: '请输入应聘者姓名' }
    ],
    certificateName: [
      { required: true, message: '请输入证书名称' }
    ],
    issuingAuthority: [
      { required: true, message: '请输入颁发机构' }
    ],
    issueDate: [
      { required: true, message: '请输入颁发时间' }
    ],
  };

  let skillCertificateForm: Partial<SkillCertificate> = {}

  const [title, setTitle] = useState('新增技能证书');

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑技能证书')
      initSkillCertificateFormById(id)
    } else {
      setTitle('新增技能证书')
      form.resetFields();
    }
  }, [visible]);

  const initSkillCertificateFormById = async (id: number) => {
    const resp: Result<SkillCertificate> = await skillCertificateApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      skillCertificateForm = resp.data
      form.setFieldsValue(resp.data);
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let skillCertificate2Save:SkillCertificate = form.getFieldsValue()
      if (id) {
        skillCertificate2Save = Object.assign(skillCertificateForm, skillCertificate2Save)
      }
      const resp: Result<void> = await skillCertificateApi.save(skillCertificate2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增技能证书')
    form.resetFields();
  };
  
  const [candidateSelectorVisible, setCandidateSelectorVisible] = useState(false);
  const findCandidate = () => {
    setCandidateSelectorVisible(true);
  }
  const handleCandidateSelected = (selectedCandidate: { candidateId?: number; candidateName?: string; }) => {
    setCandidateSelectorVisible(false)
    if (selectedCandidate && 'candidateId' in selectedCandidate) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      candidateId: selectedCandidate['candidateId'],
      candidateName: selectedCandidate['candidateName'],
      }));
    }
  };
  const handleCloseCandidateSelector = () => {
    setCandidateSelectorVisible(false)
  };

  const onBack = () => {
    onCloseSkillCertificateAdd()
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onCloseSkillCertificateAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="skillCertificateForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="candidateName" label="应聘者姓名"  rules={rules.candidateName}>
              <Input.Search placeholder="请选择应聘者姓名" onSearch={findCandidate} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="certificateName" label="证书名称" rules={rules.certificateName}>
              <Input maxLength={255} placeholder="请输入证书名称"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="issuingAuthority" label="颁发机构" rules={rules.issuingAuthority}>
              <Input maxLength={255} placeholder="请输入颁发机构"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="issueDate" label="颁发时间" rules={rules.issueDate}>
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="expiryDate" label="到期日期">
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <CandidateSelector visible={candidateSelectorVisible} onCandidateSelected={handleCandidateSelected} onCloseCandidateSelector={handleCloseCandidateSelector} />
    </Modal>
  )
}

export default SkillCertificateAdd;
